package com.asiainfo.kbisheet.components.condition
{
	import com.asiainfo.kbisheet.components.VSpace;
	import com.asiainfo.kbisheet.control.MessageControl;
	import com.asiainfo.kbisheet.model.KbsModel;
	import com.asiainfo.kbisheet.model.MessageModel;
	
	import spark.components.HGroup;
	
	[Event(name="updateConditionComplete")]
	
	/**
	 * 条件面板。
	 */
	public class ConditionPanel extends HGroup
	{
		private var messageControl:MessageControl = new MessageControl();
		
		[Bindable]
		private var kbsModel:KbsModel = KbsModel.getInstance();
		
		internal var messageModel:MessageModel = MessageModel.getInstance();
		
		public function ConditionPanel() 
		{
			super();
		}
		
		public function showConditions():void{
			if(kbsModel.conditionsXML != null){
				updateMessage("ConditionPanel:showConditions:呈现组件...");
				for each(var conditionGroupXML:XML in kbsModel.conditionsXML.conditionGroup){
					addElement(new ConditionGroup(conditionGroupXML));	
					addElement(new VSpace());
				}
				updateMessage("ConditionPanel:showConditions:初始组件数据及连接事件...");
				for each(var conditionItem:ConditionItem in kbsModel.conditionItemHandler){
					conditionItem.addEventListener("updateConditionComplete",checkUpdateConditionComplete);
					/*初始化组件数据*/
					conditionItem.initData();
					/*连接事件*/
					conditionItem.addEventListener("change",onChange);
				}
			}
			/*强制检查是否更新完成*/
			checkUpdateConditionComplete(null);
		}
		
		protected function updateMessage(message:String):void{
			messageControl.updateMessage(message);
		}
		
		/*检查是否所有ConditionItem都准备完成。*/
		private function checkUpdateConditionComplete(event:Event):void{
			for each(var conditionItem:ConditionItem in kbsModel.conditionItemHandler){
				if(!conditionItem.updateConditionCompleted){
					return;
				}
			}
			/*分配更新完成的事件*/
			var newEvent:Event = new Event("updateConditionComplete");
			dispatchEvent(newEvent);
		}
		
		/*处理条件变化*/
		private function onChange(event:Event):void{
			if(event.currentTarget is ConditionItem){
				var conditionItem:ConditionItem = ConditionItem(event.currentTarget);
				updateMessage("ConditionPanel.onChange(): id = " + conditionItem.conditionId + "; value = " + conditionItem.getAValue());
				for each(var ciOther:ConditionItem in kbsModel.conditionItemHandler){
					if(ciOther.needRefresh(conditionItem.conditionId)){
						trace("refresh:" +ciOther.conditionId);
						ciOther.initData();
					}
				}
			}
		}		
	}
}